package com.c.controller;

import com.c.pojo.entity.Account;
import com.c.service.AccountService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author bysun
 */
@Controller
public class AccountController {

    @Resource
    AccountService accountService;

    @GetMapping("/gotoAddPage")
    public String gotoAddPage() {
        return "account";
    }

    @PostMapping("/addAccount")
    public String addAccount(Account account, Model model) {
        if (StringUtils.isEmpty(account.getAccessTokenUrl()) || StringUtils.isEmpty(account.getAccountId())) {
            model.addAttribute("msg", "access_token_url和账号id不可为空");
            return "account";
        }
        accountService.addAccount(account);
        return "redirect:getAccounts";
    }

    @GetMapping("/getAccounts")
    public String getAccounts(Model model) {
        model.addAttribute("accounts", accountService.getAccounts());
        return "index";
    }

    @GetMapping("/gotoUpdatePage/{id}")
    public String gotoUpdatePage(@PathVariable("id") Integer id, Model model) {
        model.addAttribute("account", accountService.getAccount(id));
        return "/account";
    }

    @PutMapping("/addAccount")
    public String updateAccount(Account account, Model model) {
        if (account.getId() == null) {
            model.addAttribute("account");
            return "redirect:/gotoUpdatePage";
        }
        accountService.updateAccount(account);
        return "redirect:/getAccounts";
    }

    @DeleteMapping("/delAccount/{id}")
    public String delAccount(@PathVariable("id") Integer id) {
        accountService.delAccount(id);
        return "redirect:/getAccounts";
    }
}
